package fr.vod.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * 
 * @author drazanakoto
 * 
 */
public class ReceiverUnicastUDP {
	private DatagramSocket socket;

	/**
	 * 
	 * @param port
	 * @throws Exception
	 */
	public ReceiverUnicastUDP(int port) throws Exception {
		socket = new DatagramSocket(port);
	}

	public DatagramPacket receivePacket() throws Exception {
		byte[] buffer = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
		socket.receive(packet);
		return packet;
	}

	public DatagramPacket receivePacket(int timeout) throws Exception {
		byte[] buffer = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
		try {
			socket.setSoTimeout(timeout);
			socket.receive(packet);
		} catch (Exception e) {
		}
		socket.setSoTimeout(0);
		return packet;
	}

	public String receive(int timeout) throws Exception {
		byte[] buffer = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
		try {
			socket.setSoTimeout(timeout);
			socket.receive(packet);
			socket.setSoTimeout(0);
			return new String(packet.getData()).trim();
		} catch (Exception e) {
			socket.setSoTimeout(0);
			return null;
		}
	}

	public String receive() throws Exception {
		byte[] buffer = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
		socket.receive(packet);
		return new String(packet.getData()).trim();
	}
}
